package net.xju3_4.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateUtils {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 将 LocalDateTime 转换为字符串
     * @param localDateTime
     * @return
     */
    public static String format(LocalDateTime localDateTime) {
        if (localDateTime != null) {
            return localDateTime.format(formatter);
        }
        return null;
    }

    /**
     * 将字符串转换为 LocalDateTime
     * @param dateTxt
     * @return
     */
    public static LocalDateTime parseStr2LocalDateTime(String dateTxt) {
        if (dateTxt != null && dateTxt.trim().length() > 0) {
            try {
                return LocalDateTime.parse(dateTxt.trim(), formatter);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 字符串转日期类型
     * @param dateTxt
     * @return
     */
    public static Date parseStr2Date(String dateTxt){
        Date date = null;

        try {
            if(dateTxt!=null && dateTxt.trim().length()>0){
                date = simpleDateFormat.parse(dateTxt.trim());
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 日期转字符串
     * @param date
     * @return
     */
    public static String parseDate2Str(Date date){
        if(date!=null){
            return  simpleDateFormat.format(date);
        }
        return null;
    }
}